﻿using Basic.Service;
using Microsoft.AspNetCore.Mvc;
using Models.MinioFile;
using System.Threading.Tasks;

namespace Basic.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MinioFileController : ControllerBase
    {
        private readonly MinioFileService _minioFileService;

        public MinioFileController(MinioFileService minioFileService)
        {
            this._minioFileService = minioFileService;
        }

        /// <summary>
        /// a. 如果是秒传，在请求结果中会有相应的标识，比如我这里是skipUpload为true，且返回了url，代表服务器告诉我们这个文件已经有了，我直接把url给你，你不用再传了，这就是秒传。
        /// b. 如果后台返回了分片信息，这是断点续传。如图，返回的数据中有个uploaded的字段，代表这些分片是已经上传过的了，插件会自动跳过这些分片的上传。
        /// </summary>
        /// <param name="identifier"></param>
        /// <param name="totalSize"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAsync(string identifier, long totalSize, string fileName)
        {
            var model = _minioFileService.GetFileInfo(identifier, fileName,totalSize);
            if (model != null)
                return Ok(model);
            return Ok(new { Uploaded = await _minioFileService.GePartInfoAsync(identifier, totalSize, fileName), NeedMerge = true });
        }

        /// <summary>
        /// 上传分片信息
        /// </summary>
        /// <param name="partData"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> PostAsync([FromForm] MinioFilePartUpload partData)
        {
            await _minioFileService.UploadPartAsync(partData);
            return new { NeedMerge = true };
        }


        /// <summary>
        /// 合并
        /// </summary>
        /// <param name="fileCompose"></param>
        /// <returns></returns>
        [HttpPost("Compose")]
        public async Task Compose([FromBody]FileCompose  fileCompose)
        {
            await _minioFileService.Compose(fileCompose);
        }
    }
}
